#include "TubMove.h"
#include "ui_TubMove.h"
#include <QTimer>
#include "src/Manager/ThreadPool.h"
#include <QMessageBox>
#include <QFileDialog>
#include "iconhelper.h"
#include "enumfontsome.h"


TubMove::TubMove(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::TubMove)
{
    ui->setupUi(this);
    curModel=(false);
    initUIs();
}

TubMove::~TubMove()
{
    delete ui;
}

void TubMove::initUIs()
{
    radioGroup = new QButtonGroup;
    ItemModel = new QStandardItemModel(this);

    // 这里的顺序不能出问题
    radioGroup->addButton(ui->rb_nullRun);
    radioGroup->addButton(ui->rb_cap);
    radioGroup->addButton(ui->rb_weld);
    radioGroup->addButton(ui->rb_weld_cap);
    radioGroup->addButton(ui->rb_Res);
    radioGroup->setExclusive(true);
    ui->lcdNumber->setDigitCount(4);
    ui->lcdNumber->setMode(QLCDNumber::Dec);
    ui->lcdNumber->setSegmentStyle(QLCDNumber::Flat);

    ItemModel->setColumnCount(2);
    QStringList headers{"index","Pos"};
    ItemModel->setHorizontalHeaderLabels(headers);

    //ui->tb_import->setFont( IconHelper::Instance()->GetFont());
    ui->tb_import->setText(QChar(IconIdentity::icon_download));
    ui->tb_clean->setText(QChar(IconIdentity::icon_spinner));
    ui->tb_delete->setText(QChar(IconIdentity::icon_trash));
    ui->tb_takePic->setText(QChar(IconIdentity::icon_camera));
    ui->tb_goto->setText(QChar(IconIdentity::icon_location_arrow));
    ui->tb_add->setText(QChar(IconIdentity::icon_plus));

    ui->listView->setModel(ItemModel);

}

// 获取checkbox索引
int TubMove::getRadioGroupIndex()
{
    return abs(radioGroup->checkedId() + 2 ) ;
}

// 运行按钮被点击
void TubMove::on_pb_run_clicked()
{

    switch(getRadioGroupIndex()){
        case 0:
            // 空走
        if(listPos.empty() && listAxle.empty()){
            QMessageBox::warning(this, tr("运行失败"),tr("当前没有运动队列，无法空走!"),QMessageBox::Cancel);
            break;
        }else{
//            RobotHelper::GetInstance()->_robot->successived_sig.connect([this](int index){
//                ui->lcdNumber->display(index);
//            });
            if( curModel ){
                RobotHelper::GetInstance()->_robot->absoluteMove(listAxle);
            }else{
                std::ifstream ofs;
                vector<double> mtt  ;
                // ofs.open("rundata/RealData/arrive1_1.txt");
                // ofs.open("rundata/tubeMoveData/arrive.txt");
                // ofs.open("rundata/MultData/tk800-100.txt");
                // ofs.open("rundata/MultData/sp100.txt");
                // ofs.open("rundata/RealData/arrive65012.txt");
                ofs.open("rundata/weld/arrive.txt");

                if(!ofs) std::cout <<"Not File File"<<endl;
                std::string sss;
                while(std::getline(ofs,sss)){
                    int n = std::atoi(sss.c_str());
                    mtt.push_back(n);
                }

//                for(auto ir = listPos.begin();ir != listPos.end();ir++){
//                    static int cc = 0;
//                    static bool oldSta = true;
//                    if(10 <= cc){
//                        cc = 0;
//                        oldSta = !oldSta;
//                    }else{
//                       cc++;
//                    }
//                    (*ir).weld = oldSta;
//                }


                for(auto ir = listPos.begin();ir != listPos.end();ir++){
                    static int cc = 0;
                    if(16 >= cc || (38 <= cc && 52 >= cc)){
                        (*ir).weld = true;
                        // (*ir).weld = false;
                    }else {
                       (*ir).weld = false;
                    }
                    cc++;
                    if(cc >= listPos.size()){
                        cc = 0;
                    }
                }


                auto it = listPos.begin();
                (*it).v = 10;
                // RobotHelper::GetInstance()->ABSMove(listPos.at(0));
                RobotHelper::GetInstance()->RetractMove(listPos.at(0),-5,0,0);
                std::string filename = "rundata/mult/" + to_string(4396)+"-mutable-" + "Frame.log";
                //RobotHelper::GetInstance()->MultMove(listPos,filename);
                RobotHelper::GetInstance()->_robot->pathLog = true;
                weldInfo w_info;
                w_info.V_W = 16;
                w_info.V_END = 16;
                w_info.I_W = 120;
                w_info.S_W = 25;
                RobotHelper::GetInstance()->_robot->setWeldingTrue(w_info);
                RobotHelper::GetInstance()->_robot->multMove(listPos,mtt,filename);
            }
//            RobotHelper::GetInstance()->_robot->successived_sig.disconnect_all_slots();
        }
        break;
        case 1:
            if(listPos.empty()){
                QMessageBox::warning(this, tr("运行失败"),tr("当前没有Pos队列，无法空走!"),QMessageBox::Cancel);
                break;
            }
        break;
        case 2:
            if(listPos.empty()){
                QMessageBox::warning(this, tr("运行失败"),tr("当前没有Pos队列，无法空走!"),QMessageBox::Cancel);
                break;
            }
        break;
        case 3:
            if(listPos.empty()){
                QMessageBox::warning(this, tr("运行失败"),tr("当前没有Pos队列，无法空走!"),QMessageBox::Cancel);
                break;
            }
        break;
        case 4:     // 摸点
//            if(aPos_vect.empty()){
//                QMessageBox::warning(this, tr("运行失败"),tr("当前没有产生格点!"),QMessageBox::Cancel);
//            }else{
//                ImgProvider::GetInstance()->callImagePoss(aPos_vect);
//            }
        break;
        default:
        break;
    }
}


void TubMove::on_tb_clean_clicked()
{
    ItemModel->clear();
    listPos.clear();
    listAxle.clear();
}

void TubMove::on_tb_takePic_clicked()
{
    try {
        auto pic = CameraHelper::GetInstance()->GetPictrue();
        auto dist = "runData/Pic/"+DateTime::getFullTime();
        cv::imwrite(dist,pic);
    } catch (...) {
        pushWarn("尝试获取一张照片失败!",MU_ERROR_MODULE_CAM);
    }
}

void TubMove::on_tb_delete_clicked()
{
    QModelIndex index = ui->listView->currentIndex();
    ItemModel->removeRow(index.row());
    int indewx = 0;
    if(curModel){   // 如果是轴模式
        for(auto iter=listAxle.begin();iter!=listAxle.end();iter++){        //从vector中删除指定的某一个元素
            if(indewx == index.row()){
                listAxle.erase(iter);
                break;
            }
        }
    }else{   // 如果是Base模式
        for(auto iter=listPos.begin();iter!=listPos.end();iter++){        //从vector中删除指定的某一个元素
            if(indewx == index.row()){
                listPos.erase(iter);
                break;
            }
        }
    }
}

void TubMove::on_tb_goto_clicked()
{
    if(curModel){
        RobotHelper::GetInstance()->ABSMoveAxis(_curSelectAxle,SysMembers::GetInstance()->debugRobotSpeed);
    }else{
        RobotHelper::GetInstance()->ABSMove(_curSelect,SysMembers::GetInstance()->debugRobotSpeed);
    }
}

void TubMove::on_tb_add_clicked()
{
    QStandardItem *item = new QStandardItem;
    ItemModel->appendRow(item);
//    QModelIndex index ;
//    ui->listView->setCurrentIndex(index.sibling(0,0));
}

void TubMove::on_tb_import_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,
          tr("选择文件"), "rundata/Ready", tr("Pos Files (*.*)"));
    std::ifstream infile(fileName.toStdString());
    std::string line;
    static bool isCheck = false;
    while (std::getline(infile, line)){
        if(!isCheck){
            bool ret = std::string::npos  == line.find("typeAxle");
            !ret ? curModel = true:curModel = false;
            !ret ? ui->lb_model->setText(fileName.section("/",-1) + "\t" + "轴运动模式"):ui->lb_model->setText(fileName.section("/",-1)+ "\t"  +"Base运动模式");
        }else {
            if(line.empty()) continue;
            curModel ? listAxle.push_back(RobotAxle::instance(line)):listPos.push_back(RobotPos::instance(line)) ;
        }
        isCheck = true;
    }
    updateSportList();
    isCheck = false;
}

void TubMove::on_cb_MoveType_activated(int index)
{
    if(2 == index){
        curModel = true;
    }else {
        curModel = false;
    }
}


// 运动队列更新
void TubMove::updateSportList()
{
    ItemModel->clear();
    if(curModel){
        for(auto &a:listAxle){
            QStandardItem *item = new QStandardItem(QString::fromStdString(a.toStr()));
            ItemModel->appendRow(item);
        }
    }else{
        for(auto &a:listPos){
            QStandardItem *item = new QStandardItem(QString::fromStdString(a.toStr()));
            ItemModel->appendRow(item);
        }
    }
}


// 运动list被点击
void TubMove::on_listView_clicked(const QModelIndex &index)
{
    // int row_num = index.row();
    if(curModel){
        _curSelectAxle = RobotAxle::instance(ItemModel->data(index).toString().toStdString());
        updateSelect(_curSelectAxle);
    }else{
        RobotPos d;
        d.instance(ItemModel->data(index).toString().toStdString());
        updateSelect(d);
        _curSelect = d;
    }

}



// 更新选择的pos点
void TubMove::updateSelect(RobotPos d)
{
    ui->lb_x_2->setText(QString::number(d.x));
    ui->lb_y_2->setText(QString::number(d.y));
    ui->lb_z_2->setText(QString::number(d.z));
    ui->lb_a_2->setText(QString::number(d.a));
    ui->lb_b_2->setText(QString::number(d.b));
    ui->lb_c_2->setText(QString::number(d.c));
}

void TubMove::updateSelect(RobotAxle d)
{
    ui->lb_x_2->setText(QString::number(d.a1));
    ui->lb_y_2->setText(QString::number(d.a2));
    ui->lb_z_2->setText(QString::number(d.a3));
    ui->lb_a_2->setText(QString::number(d.a4));
    ui->lb_b_2->setText(QString::number(d.a5));
    ui->lb_c_2->setText(QString::number(d.a6));
}
